//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxScanCallViewController.h"

@implementation PxScanCallViewController {
    int type;
}

static const char *kScanQRCodeQueueName = "ScanQRCodeQueue";

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        type = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super setLogoTitleViewWithTitle:@"电话通知"];
    [self.contentView setScrollEnabled:NO];
    
    CGRect scanCrop = CGRectMake([PxGlobal getCustomerWidth:45], [PxGlobal getCustomerHeight:100], [PxGlobal getCustomerWidth:230], [PxGlobal getCustomerHeight:165]);
    _readerView = [[PxReaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height )];
    _readerView.scanRect = scanCrop;
    _readerView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_readerView];
    
    [self setRightBtn:@"手动"];
}

-(void)setRightBtn:(NSString *) title
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    [navBarRightButton setTitle:title];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

- (void)navBarRightBtnAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请输入运单号"] preferredStyle: UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"请输入运单号...";
    }];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        UITextField *textField = alertController.textFields.firstObject;
        [self getPhoneNo:textField.text];
    }];
    UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        
    }];
    [alertController addAction:OKAction];
    [alertController addAction:CancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (BOOL)startReading
{
    _isReading = YES;
    // 获取 AVCaptureDevice 实例
    NSError * error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 初始化输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    // 创建会话
    self.session = [[AVCaptureSession alloc] init];
    // 添加输入流
    [self.session addInput:input];
    // 初始化输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    // 添加输出流
    [self.session addOutput:captureMetadataOutput];
    
    // 创建dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    // 设置元数据类型 AVMetadataObjectTypeQRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code,
        AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code, nil]];
    
    // 创建输出对象
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:_readerView.bounds];
    [self.view.layer insertSublayer:_videoPreviewLayer atIndex:0];
//    [_readerView.layer insertSublayer:_videoPreviewLayer atIndex:10];
//    [_readerView.layer addSublayer:_videoPreviewLayer];
    
    //用户是否允许启用摄像头
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted)
        {
            //Granted access to mediaType
            [self.session startRunning];
        }
        else
        {
            //Not granted access to mediaType
            dispatch_async(dispatch_get_main_queue(), ^{
                [[[UIAlertView alloc] initWithTitle:@"AVCam!"
                                            message:@"AVCam doesn't have permission to use Camera, please change privacy settings"
                                           delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil] show];
            });
        }
    }];
    
    return YES;
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result = metadataObj.stringValue;
        [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:result waitUntilDone:NO];
    }
}

-(void)getPhoneNo:(NSString *)waybillNo
{
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_WAYBILL_INFO_QUERY;
    [cmd.paramDic addEntriesFromDictionary:@{@"waybillNo":waybillNo}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        NSDictionary *result = dic[RESULT_DATA];
        NSString *phoneNo = result[@"receiverPhone"];
        
        NSDictionary *task = result[@"task"];
        NSString *appointTime = task[@"appointTime"];
        NSString *taskPhone = task[@"phone"];
        if (appointTime && appointTime.length>0 && taskPhone && taskPhone.length>0) {
            NSString *msg = [NSString stringWithFormat:@"此运单为预约运单，预约送件时间为%@。预约电话为%@，是否要拨打预约电话？", appointTime, taskPhone];
            [self showAlertView:msg andPhoneNo:taskPhone];
        } else {
            NSString *msg = [NSString stringWithFormat:@"拨打 %@", phoneNo];
            [self showAlertView:msg andPhoneNo:phoneNo];
        }
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        NSString *resultStr = dic[RESULT_DESC];
        if (resultStr.length <= 0)
            resultStr = @"无此运单号";
        
        [LLAlertService alertWithTip:resultStr];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

-(void)showAlertView:(NSString *)msg andPhoneNo:(NSString *)phoneNo
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle: UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        NSString *strPhone = [NSString stringWithFormat:@"tel://%@", phoneNo];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strPhone]];
    }];
    [alertController addAction:OKAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)reportScanResult:(NSString *)result
{
    LLDLog(@"result:%@", result);
    if (!_isReading)
        return;
    _isReading = NO;
    [self getPhoneNo:result];
}

- (void)stopReading
{
    // 停止会话
    [self.session stopRunning];
    self.session = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    type = [self.incomingParam[@"type"] intValue];
    [self startReading];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    _isReading = NO;
    [self stopReading];
}

@end
